;(function () {
  const errorCache = new Map() // 使用Map记录错误和它们的时间戳
  const REPORT_THRESHOLD = 5 * 60 * 1000 // 5分钟（以毫秒为单位）

  // 设备解析器
  const deviceInfo = new UAParser().getResult()

  function getAdditionalInfo() {
    const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection
    const connectionType = connection ? connection.effectiveType : 'unknown'
    const screenWidth = window.screen.width
    const screenHeight = window.screen.height
    return {
      device: {
        screenSize: screenWidth + 'x' + screenHeight,
        online: navigator.onLine,
        connectionType,
        ...deviceInfo,
      },
      referrer: document.referrer,
      currentUrl: window.location.href,
      userAgent: navigator.userAgent,
    }
  }

  const originalConsoleError = console.error
  console.error = function (...args) {
    reportError({
      message: args.join(' '),
      source: 'console',
      stack: new Error().stack,
      // type: 'console_error',
      type: 1,
    })
    originalConsoleError.apply(console, args)
  }

  window.addEventListener(
    'error',
    (event) => {
      if (event.target && (event.target.src || event.target.href)) {
        // 静态资源加载错误
        reportError({
          message: `Failed to load resource: ${event.target.src || event.target.href}`,
          source: event.target.tagName,
          stack: 'no stack available',
          // type: 'resource_error',
          type: 3,
          target: `${event.target.src || event.target.href}`,
        })
      } else {
        // JavaScript 错误
        reportError({
          message: event.message,
          source: event.filename,
          stack: event.error ? event.error.stack : 'no stack available',
          lineno: event.lineno,
          colno: event.colno,
          // type: 'js_error',
          type: 1,
        })
      }
    },
    true
  )

  window.addEventListener('unhandledrejection', (event) => {
    reportError({
      message: event.reason && event.reason.message ? event.reason.message : 'Unhandled Rejection',
      source: 'unhandledrejection',
      stack: event.reason && event.reason.stack ? event.reason.stack : 'no stack available',
      // type: 'promise_rejection',
      type: 1,
    })
  })

  function reportError(errorDetails) {
    const currentTime = Date.now()
    const errorString = `${errorDetails.type}: ${errorDetails.source}: ${errorDetails.message} at ${errorDetails.stack}`
    if (errorCache.has(errorString) && currentTime - errorCache.get(errorString) < REPORT_THRESHOLD) {
      return
    }

    errorCache.set(errorString, currentTime)

    const additionalInfo = getAdditionalInfo()
    const errorData = {
      timestamp: new Date().toISOString(),
      ...additionalInfo,
      ...errorDetails,
    }
    if (!isHttpError(errorData.message)) {
      // console.log('Error reported:', errorData)
      // 以下可以替换为实际的上报错误的逻辑，比如发送请求到后台。
      const zkdtMonitorData = window.zkdtMonitor ? window.zkdtMonitor.data : {}
      const paylod = {
        userId: zkdtMonitorData.userId || '',
        userName: zkdtMonitorData.userName || '',
        proID: zkdtMonitorData.proID || '',
        proVersion: zkdtMonitorData.proVersion || '',
        env: zkdtMonitorData.env || 'pro',
        errType: errorData.type,
        page: errorData.currentUrl,
        content: JSON.stringify(errorData),
      }
      fetch('https://gateway.matefarm.net/v3/config/statistic/add', {
        method: 'POST',
        body: JSON.stringify(paylod),
        headers: { 'Content-Type': 'application/json' },
      }).catch()
    }
  }

  function isHttpError(message) {
    const httpErrorKeywords = ['Failed to fetch', 'Network Error', 'Request failed', 'timeout']
    return httpErrorKeywords.some((keyword) => message.includes(keyword))
  }
  window.zkdtMonitor = {
    data: {},
    init(data) {
      this.data = JSON.parse(JSON.stringify(data)) // 深拷贝
    },
  }
})()
